package com.example.ruiji.filter;

import com.example.ruiji.utils.token.JwtToken;
import com.example.ruiji.utils.token.MyTokenUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Author:BaiYiChen
 * Date:2022/5/3 14:16
 *
 * @author BaiYiChen
 */
public class JwtTokenFilter2 extends BasicHttpAuthenticationFilter {
  @Override
  protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
    if (isLoginAttempt(request, response)){
      try {
        executeLogin(request, response);
        return true;
      } catch (Exception e) {
        e.printStackTrace();
        return false;
      }
    }
    return true;
  }
  
  @Override
  protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
    HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
    String parameter = httpServletRequest.getParameter(MyTokenUtils.ACCESS_TOKEN);
    
    return !StringUtils.isEmpty(parameter);
  }
  
  @Override
  protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
    HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
    String parameter = httpServletRequest.getParameter(MyTokenUtils.ACCESS_TOKEN);
    getSubject(request, response).login(new JwtToken(parameter));
    
    return true;
  }
}
